package com.linln.admin.member.controller;

import java.math.BigDecimal;
import java.net.InetAddress;
import java.util.Date;
import java.util.List;

import com.linln.common.enums.ResultEnum;
import com.linln.common.exception.ResultException;
import com.linln.modules.member.domain.MemberAgentMoneyChange;
import com.linln.modules.member.service.MemberAgentMoneyChangeService;
import com.linln.modules.system.domain.Area;
import com.linln.modules.system.service.AreaService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.binarywang.wxpay.bean.entpay.EntPayQueryResult;
import com.github.binarywang.wxpay.bean.entpay.EntPayRequest;
import com.github.binarywang.wxpay.bean.entpay.EntPayResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.ToolUtil;
import com.linln.common.vo.ResultVo;
import com.linln.modules.member.domain.MemberAgent;
import com.linln.modules.member.domain.MemberAgentMoney;
import com.linln.modules.member.domain.MemberInfo;
import com.linln.modules.member.service.MemberAgentMoneyService;
import com.linln.modules.member.service.MemberAgentService;
import com.linln.modules.member.service.MemberInfoService;
import com.linln.wxapi.config.WeChatPayProperties;

import javax.persistence.criteria.CriteriaBuilder;

/**
 * @author hct
 * @date 2019/09/12
 */
@Controller
@RequestMapping("/member/agentmoney")
public class MemberAgentMoneyController {

    @Autowired
    private MemberAgentMoneyService memberAgentMoneyService;
    @Autowired
    private AreaService areaService;

    @Autowired
    private MemberAgentService memberAgentService;

    @Autowired
    private MemberAgentMoneyChangeService memberAgentMoneyChangeService;
  
    
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    WeChatPayProperties weChatPayProperties;

    
    /**
     * 列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("member:agentmoney:index")
    public String index(Model model, MemberAgentMoney membermoney) {

        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching();
        // 获取数据列表
        Example<MemberAgentMoney> example = Example.of(membermoney, matcher);
        Page<MemberAgentMoney> list = memberAgentMoneyService.getPageList(example);
        List<MemberAgentMoney> content = list.getContent();
        for (MemberAgentMoney memberAgentMoney : content
        ) {
            if(memberAgentMoney==null) continue;
            Area area = areaService.findByCode(memberAgentMoney.getArea());
            if(area != null){
                Area parea = areaService.getById(area.getPid());
                memberAgentMoney.setAreaName(parea.getName()+area.getName());
                /*if(parea != null){
                    memberAgentMoney.setArea(parea.getName());
                }*/
            }
        }
        // 封装数据
        model.addAttribute("list", content);
        model.addAttribute("page", list);
        return "/member/agentmoney/index";
    }

    /**
     * 列表页面
     */
    @GetMapping("/applyindex")
    @RequiresPermissions("member:agentmoney:applyindex")
    public String applyindex(Model model, MemberAgentMoney membermoney) {

        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching();
        membermoney.setStatus(0);
        // 获取数据列表
        Example<MemberAgentMoney> example = Example.of(membermoney, matcher);
        Page<MemberAgentMoney> list = memberAgentMoneyService.getPageList(example);

        // 封装数据
        model.addAttribute("list", list.getContent());
        model.addAttribute("page", list);
        return "/member/agentmoney/applyindex";
    }
    /**
     * 跳转到添加页面
     */
    @GetMapping("/withdrawal")
    public String withdrawal() {
        return "/member/agentmoney/withdrawal";
    }


    /**
     * 管理员提现提现
     * @param model
     * @return
     */
    @PostMapping("adminWithdrawal")
    @ResponseBody
    public ResultVo adminWithdrawal(Model model, Double bemoney){
        if(bemoney.doubleValue() < 1d){
            throw new ResultException(ResultEnum.LESS_ONE);
        }
        if(bemoney.doubleValue() > 5000d){
            throw new ResultException(ResultEnum.GREATER_FIVETHOUSAND);
        }
        MemberAgent memberAgent = memberAgentService.getByArea("000000");
        MemberInfo memberinfo=memberAgent.getMember();
        Double curmoney = memberAgent.getCurmoney();
        EntPayRequest entPayRequest = new EntPayRequest();
        entPayRequest.setAppid(weChatPayProperties.getAppId());
        entPayRequest.setMchId(weChatPayProperties.getMchId());
        entPayRequest.setPartnerTradeNo(ToolUtil.getRandomString(32));
        entPayRequest.setOpenid(memberinfo.getOpenid());
        entPayRequest.setCheckName("NO_CHECK");
        entPayRequest.setAmount(adminYuanToFeeToPay(new BigDecimal(bemoney)));
        entPayRequest.setDescription(new Date()+"一笔支付费用");
        entPayRequest.setSpbillCreateIp(InetAddress.getLoopbackAddress().getHostAddress());
        try {
            EntPayResult entPayResult=wxPayService.getEntPayService().entPay(entPayRequest);
            if(entPayResult.getResultCode().equals("SUCCESS") && entPayResult.getReturnCode().equals("SUCCESS")) {
                //设置提现默认状态
                Integer status=1;
                MemberAgentMoney memberAgentMoney=new MemberAgentMoney();
                memberAgentMoney.setStatus(status);
                memberAgentMoney.setPaymoneyDate(new Date());
                memberAgentMoney.setPaymoney(new BigDecimal(bemoney).doubleValue());
                memberAgentMoney.setReasondesc("超级管理员提现");
                memberAgentMoney.setCurmoney(bemoney);
                //记录我真实的收入
                memberAgentMoney.setOwnermoney(0d);
                memberAgentMoneyService.save(memberAgentMoney);
                //代理商提现成功后，平台的手续费收入也会汇总到系统里面
                MemberAgent agent=memberAgentService.getById(1L);
                agent.setCurmoney(agent.getCurmoney()-bemoney);
                memberAgentService.save(agent);
                MemberAgentMoneyChange memberAgentMoneyChange=new MemberAgentMoneyChange();
                memberAgentMoneyChange.setArea(memberAgent.getArea());
                memberAgentMoneyChange.setAreaName(memberAgent.getArea());
                memberAgentMoneyChange.setStatus(1);
                memberAgentMoneyChange.setPreMoney(curmoney);
                memberAgentMoneyChange.setChangemoney(bemoney.doubleValue());
                memberAgentMoneyChange.setLastmoney(agent.getCurmoney());
                memberAgentMoneyChange.setType(null);
                memberAgentMoneyChange.setTypeid(null);
                memberAgentMoneyChange.setStatetype(3);
                memberAgentMoneyChange.setCreateDate(new Date());
                memberAgentMoneyChange.setUpdateDate(new Date());
                memberAgentMoneyChangeService.saveMemberAgentMoneyChange(memberAgentMoneyChange);
            }else{
                System.out.println("youwenti ");
                if(entPayResult.getResultCode().equals("FAIL") && entPayResult.getReturnCode().equals("SUCCESS")){
                    return ResultVoUtil.error(entPayResult.getErrCodeDes());
                }
                throw new ResultException(-1,entPayResult.getReturnMsg());
            }
        } catch (WxPayException e) {
            e.printStackTrace();
            throw new ResultException(-1,"支付异常");
        }
        return ResultVoUtil.SAVE_SUCCESS;
    }

    /**
     * 流水记录
     * @param model
     * @return
     */
    @GetMapping("adminWithdrawalFlow")
    public String adminWithdrawalFlow(Model model){
        MemberAgentMoneyChange memberAgentMoneyChange=new MemberAgentMoneyChange();
        memberAgentMoneyChange.setArea("000000");
        Page<MemberAgentMoneyChange> memberAgentMoneyChanges = memberAgentMoneyChangeService.selectMemberAgentMoneyChange(memberAgentMoneyChange);
        MemberAgent byMemberIdAndArea = memberAgentService.getByArea("000000");
        model.addAttribute("amdinMessage",byMemberIdAndArea);
        model.addAttribute("list",memberAgentMoneyChanges.getContent());
        model.addAttribute("page",memberAgentMoneyChanges);
        return "/member/agentmoney/adminWithdrawal";
    }


   
    /**
     * 审核
     * 申请提现价格 0代表申请 1代表同意 2代表拒绝
     * @param
     */
    @RequestMapping(value = "approval",method= {RequestMethod.POST,RequestMethod.GET})
    @RequiresPermissions({"member:agentmoney:add", "member:agentmoney:edit"})
    @ResponseBody
    public ResultVo approval(MemberAgentMoney memberInfo,Integer status,Integer type) {
        // 复制保留无需修改的数据
        MemberAgentMoney bemoney = memberAgentMoneyService.getById(memberInfo.getId());
        MemberInfo memberinfo=bemoney.getMemberagent().getMember();
        EntPayRequest entPayRequest = new EntPayRequest();
        entPayRequest.setAppid(weChatPayProperties.getAppId());
        entPayRequest.setMchId(weChatPayProperties.getMchId());
        entPayRequest.setPartnerTradeNo(bemoney.getOrderCode());
        entPayRequest.setOpenid(memberinfo.getOpenid());
        entPayRequest.setCheckName("NO_CHECK");
        entPayRequest.setAmount(yuanToFeeToPay(new BigDecimal(bemoney.getCurmoney())));
        entPayRequest.setDescription(new Date()+"一笔支付费用");
        entPayRequest.setSpbillCreateIp(InetAddress.getLoopbackAddress().getHostAddress());
         if(bemoney.getStatus().intValue()>0){
             return ResultVoUtil.error("已支付完成或者已被拒绝,请联系管理员");
         }
        // 保存数据
        if(status==1) {
        	try {
        	       //本处对接微信余额进行支付
                    EntPayResult entPayResult=wxPayService.getEntPayService().entPay(entPayRequest);
                    System.out.println("entPayResult>>>>>"+entPayResult);
                    //测试！！！！！！！不可提交上线
//                    EntPayResult entPayResult=new EntPayResult();
//                    entPayResult.setResultCode("SUCCESS");
//                    entPayResult.setReturnCode("SUCCESS");
                     //测试！！！！！！！不可提交上线
                    if(entPayResult.getResultCode().equals("SUCCESS") && entPayResult.getReturnCode().equals("SUCCESS")) {
                        bemoney.setStatus(status);
                        bemoney.setPaymoneyDate(new Date());
                        bemoney.setPaymoney(yuanToFeeToPayDouble(new BigDecimal(bemoney.getCurmoney())));
                        bemoney.setReasondesc("同意同时进行微信支付");
                        //记录我真实的收入
                        bemoney.setOwnermoney(yuanToFeeToOwnInfoDouble(new BigDecimal(bemoney.getCurmoney())));
                        memberAgentMoneyService.save(bemoney);
                        //代理商提现成功后，平台的手续费收入也会汇总到系统里面
                        MemberAgent agent=memberAgentService.getById(1L);
                        Double curmoney=agent.getAllmoney();
                        agent.setAllmoney(agent.getAllmoney()+bemoney.getOwnermoney());
                        agent.setCurmoney(agent.getCurmoney()+bemoney.getOwnermoney());
                        memberAgentService.save(agent);
                       // =====================================================================================
                        MemberAgentMoneyChange memberAgentMoneyChange=new MemberAgentMoneyChange();
                        memberAgentMoneyChange.setArea(agent.getArea());
                        memberAgentMoneyChange.setAreaName(agent.getArea());
                        memberAgentMoneyChange.setStatus(1);
                        memberAgentMoneyChange.setPreMoney(curmoney);
                        memberAgentMoneyChange.setChangemoney(bemoney.getOwnermoney());
                        memberAgentMoneyChange.setLastmoney(agent.getCurmoney());
                        memberAgentMoneyChange.setType(null);
                        memberAgentMoneyChange.setTypeid(null);
                        memberAgentMoneyChange.setStatetype(1);
                        memberAgentMoneyChange.setCreateDate(new Date());
                        memberAgentMoneyChange.setUpdateDate(new Date());
                        memberAgentMoneyChangeService.saveMemberAgentMoneyChange(memberAgentMoneyChange);
                    }else {
                        System.out.println("youwenti ");
                        if(entPayResult.getResultCode().equals("FAIL") && entPayResult.getReturnCode().equals("SUCCESS")){
                            return ResultVoUtil.error(entPayResult.getErrCodeDes());
                        }
                    }

        	} catch (WxPayException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
                System.out.println("youwenti ");
                return ResultVoUtil.error(e.getErrCodeDes());
			}catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.println("youwenti ");
                return ResultVoUtil.error("支付异常");
            }

        }else if(status==3){//代表线下已经支付过了 本处只做记录
            bemoney.setStatus(1);
            bemoney.setPaymoneyDate(new Date());
            bemoney.setReasondesc("线下支付过的");
            bemoney.setPaymoney(yuanToFeeToPayDouble(new BigDecimal(bemoney.getCurmoney())));
            bemoney.setOwnermoney(yuanToFeeToOwnInfoDouble(new BigDecimal(bemoney.getCurmoney())));
            memberAgentMoneyService.save(bemoney);
            //代理商提现成功后，平台的手续费收入也会汇总到系统里面
            MemberAgent agent=memberAgentService.getById(1L);
            agent.setAllmoney(agent.getAllmoney()+bemoney.getOwnermoney());
            agent.setCurmoney(agent.getCurmoney()+bemoney.getOwnermoney());
            memberAgentService.save(agent);
        }else {
        	//拒绝给退回相应的数据操作,将余额给代理商退回去
            bemoney.setReasondesc("拒绝支付的");
            bemoney.setStatus(status);
		    memberAgentMoneyService.save(bemoney);
		    MemberAgent memeragent= bemoney.getMemberagent();
		    memeragent.setCurmoney(memeragent.getCurmoney()+bemoney.getCurmoney());
		    memberAgentService.save(memeragent);
        }
        return ResultVoUtil.SAVE_SUCCESS;
    }
    
    /**
     * 1块钱转为 100 分
     * 元转分
     *
     * @param bigDecimal 钱数目
     * @return 分
     */
    private int yuanToFee(BigDecimal bigDecimal) {
        return bigDecimal.multiply(new BigDecimal(100)).intValue();
    }

    /**
     * 超级管理员金额转换
     * @param bigDecimal
     * @return
     */
    private int adminYuanToFeeToPay(BigDecimal bigDecimal){
        return bigDecimal.multiply(new BigDecimal(100)).intValue();
    }

    /**
     * 超级管理员金额转换
     * @param bigDecimal
     * @return
     */
    private Double adminYuanToFeeToPayDoubleQianSan(BigDecimal bigDecimal) {
        return bigDecimal.multiply(new BigDecimal(100)).doubleValue();
    }

    /**
     * 支付给代理商90%  平台扣除10.6%的手续费
     * @param bigDecimal
     * @return
     */
    private int yuanToFeeToPay(BigDecimal bigDecimal) {
        return bigDecimal.multiply(new BigDecimal(100)).multiply(new BigDecimal("0.9")).multiply(new BigDecimal("0.997")).intValue();
    }
    //用户可提现额度为申请额度的90%的千分之997
    private Double yuanToFeeToPayDouble(BigDecimal bigDecimal) {
        return bigDecimal.multiply(new BigDecimal(100)).multiply(new BigDecimal("0.9")).multiply(new BigDecimal("0.997")).multiply(new BigDecimal("0.01")).doubleValue();
    }
    //用户部分的千分之三
    private Double yuanToFeeToPayDoubleQianSan(BigDecimal bigDecimal) {
        return bigDecimal.multiply(new BigDecimal(100)).multiply(new BigDecimal("0.9")).multiply(new BigDecimal("0.003")).multiply(new BigDecimal("0.01")).doubleValue();
    }

    private Double yuanToFeeToOwnDouble(BigDecimal bigDecimal) {
        return bigDecimal.multiply(new BigDecimal(100)).multiply(new BigDecimal("0.1")).multiply(new BigDecimal("0.01")).doubleValue();
    }
    private Double yuanToFeeToOwnDoubleQianliu(BigDecimal bigDecimal) {
        return bigDecimal.multiply(new BigDecimal(100)).multiply(new BigDecimal("0.1")).multiply(new BigDecimal("0.994")).multiply(new BigDecimal("0.01")).doubleValue();
    }
    private Double yuanToFeeToOwnInfoDouble(BigDecimal bigDecimal) {
        return new BigDecimal(yuanToFeeToOwnDoubleQianliu(bigDecimal)).subtract(new BigDecimal(yuanToFeeToPayDoubleQianSan(bigDecimal))).doubleValue();
    }
    /**
     * <pre>
     * 查询企业付款API
     * 用于商户的企业付款操作进行结果查询，返回付款操作详细结果。
     * 文档详见:https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_3
     * 接口链接：https://api.mch.weixin.qq.com/mmpaymkttransfers/gettransferinfo
     * </pre>
     *
     * @param partnerTradeNo 商户订单号
     */
     @GetMapping("/queryEntPay/{partnerTradeNo}")
    public EntPayQueryResult queryEntPay(@PathVariable String partnerTradeNo) throws WxPayException {
      return this.wxPayService.getEntPayService().queryEntPay(partnerTradeNo);
    }

    /**
     * 跳转到详细页面
     */
    @GetMapping("/detail/{id}")
    @RequiresPermissions("member:memberInfo:detail")
    public String toDetail(@PathVariable("id") MemberAgentMoney membermoney, Model model) {
        model.addAttribute("memberMoney",membermoney);
        MemberAgent memberAgent= membermoney.getMemberagent();
        model.addAttribute("memberAgent",memberAgent);
        return "/member/agentmoney/detail";
    }

  
}